package com.lcf.study.leetcode;

import com.lcf.study.model.ListNode2;

import java.util.*;

/**
 * Created by 哈兹米 on 2022-10-31.
 * 429. N叉树的层次遍历
 * <p>
 * 给定一个 N 叉树，返回其节点值的层序遍历。（即从左到右，逐层遍历）。
 * 树的序列化输入是用层序遍历，每组子节点都由 null 值分隔（参见示例）。
 * <p>
 * 例如:
 * 给定二叉树: [3,9,20,null,null,15,7],
 * <p>
 *        1
 *      / | \
 *     3  2  4
 *   /  \
 *  5   6
 * 返回其层次遍历结果：
 * <p>
 * 输入：root = [1,null,3,2,4,null,5,6]
 * 输出：[[1],[3,2,4],[5,6]]
 * 输入：root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
 * 输出：[[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
 * <p>
 * 链接：https://leetcode.cn/problems/n-ary-tree-level-order-traversal
 */
public class _429_LevelOrder {

    public static void main(String[] args) {
        _429_LevelOrder levelOrder = new _429_LevelOrder();
        ListNode2 listNode = new ListNode2(1);

        ListNode2 listNode1 = new ListNode2(3);
        ListNode2 listNode2 = new ListNode2(2);
        ListNode2 listNode3 = new ListNode2(4);

        ListNode2 listNode11 = new ListNode2(5);
        ListNode2 listNode12 = new ListNode2(6);

        List<ListNode2> level2 = new ArrayList<>();
        level2.add(listNode11);
        level2.add(listNode12);
        listNode1.children = level2;

        List<ListNode2> level1 = new ArrayList<>();
        level1.add(listNode1);
        level1.add(listNode2);
        level1.add(listNode3);
        listNode.children = level1;


        List<List<Integer>> result = levelOrder.levelOrder(listNode);
        if (result != null) {
            for (List<Integer> parent : result) {
                System.out.println("---------------");
                if (null == parent) {
                    continue;
                }
                System.out.print("[");
                for (Integer child : parent) {
                    System.out.print(child + "  ");
                }
                System.out.print("]");
                System.out.println();
                System.out.println("---------------");
            }
        }
    }

    public List<List<Integer>> levelOrder(ListNode2 root) {
        List<List<Integer>> result = new LinkedList<>();
        if (null == root) {
            return result;
        }
        Queue<ListNode2> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int count = queue.size();
            List<Integer> level = new ArrayList<Integer>();
            for (int i = 0; i < count; i++) {
                ListNode2 cur = queue.poll();
                if (null == cur) {
                    continue;
                }
                level.add(cur.val);
                if (cur.children != null && cur.children.size() > 0) {
                    for (ListNode2 child : cur.children) {
                        queue.offer(child);
                    }
                }
            }
            result.add(level);
        }

        return result;
    }
}
